package br.edu.unibratec.viagemfacil;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class FraseDB {

	private DBHelper helper;
	
	public FraseDB(Context contexto){
		helper = new DBHelper(contexto);
	}
	
	public long inserir(Frase frase){
		SQLiteDatabase db = helper.getWritableDatabase();
		
		ContentValues valores = valoresPorFrase(frase);
		
		long id = db.insert("frase", null, valores);
		frase.id = id;
		frase.favorito = true;
		
		db.close();
		
		return id;
	}
	
	private ContentValues valoresPorFrase(Frase frase) {
		ContentValues valores = new ContentValues();
		valores.put("fraseOriginal", frase.fraseOriginal);
		valores.put("fraseTraduzida", frase.fraseTraduzida);
		return valores;
	}
	
	public int atualizar(Frase frase){
		SQLiteDatabase db = helper.getWritableDatabase();
		
		ContentValues valores = valoresPorFrase(frase);
		
		int rows = db.update("frase", valores, "_id = ?", 
				new String[]{ String.valueOf(frase.id) });
		
		db.close();
		
		return rows;
	}
	
	public int excluir(Frase frase){
		SQLiteDatabase db = helper.getWritableDatabase();
		
		int rows = db.delete("frase", "_id = " + frase.id, null);
		frase.favorito = false;
		
		db.close();
		
		return rows;
	}
	
	public List<Frase> todosAsFrases(){
		List<Frase> frases = new ArrayList<Frase>();
		
		SQLiteDatabase db = helper.getReadableDatabase();
		
		Cursor cursor = db.rawQuery(
				"select * from frase", null);
		
		while(cursor.moveToNext()){
			Frase frase = preencherFrase(cursor);
			frases.add(frase);
		}
		cursor.close();
		db.close();
		return frases;
	}
	
	private Frase preencherFrase(Cursor cursor) {
		long id 	          = cursor.getLong(0);
		String fraseOriginal  = cursor.getString(1);
		String fraseTraduzida = cursor.getString(2);
		
		Frase frase = new Frase(
				id,
				fraseOriginal,
				fraseTraduzida
			);
		
		frase.favorito = true;
		
		return frase;
	}
}